package tron

import (
	"encoding/json"
	"fisherman/common/http"
	"fisherman/common/logger"
	"fisherman/main/cfg"
	"strconv"
	"time"
)

type Block struct {
	BlockID      string         `json:"blockID"`
	BlockHeader  *BlockHeader   `json:"block_header"`
	Transactions []*Transaction `json:"transactions"`
}

type BlockHeader struct {
	RawData *RawData `json:"raw_data"`
}

type RawData struct {
	Number int64 `json:"number"`
}

type Transaction struct {
	RawData    *TxRawData `json:"raw_data"`
	RawDataHex string     `json:"raw_data_hex"`
	Rets       []*Ret     `json:"ret"`
	Signatures []string   `json:"signature"`
	TxID       string     `json:"txID"`
}

type TxRawData struct {
	Contracts []*Contract `json:"contract"`
}

type Ret struct {
	ContractRet string `json:"contractRet"`
}

type Contract struct {
	Parameter *Parameter `json:"parameter"`
	Type      string     `json:"type"`
}

type Parameter struct {
	Value *Value `json:"value"`
}

type Value struct {
	ContractAddress string `json:"contract_address"`
	Data            string `json:"data"`
	OwnerAddress    string `json:"owner_address"`
}

var (
	lastSendTGTime int
)

func LoadLastBlock() (block *Block) {
	rsp := http.PostJsonD(cfg.GetAPI()+"/wallet/getblock", map[string]any{"detail": true})
	err := json.Unmarshal([]byte(rsp), &block)
	if err != nil {
		block = nil
		if lastSendTGTime < time.Now().Second() {
			log.Errorf("LoadLastBlock():解析Json到Block到到对象失败：%s 错误：%v", rsp, err)
			lastSendTGTime = time.Now().Second() + 10
		}
	}
	return
}

func LoadBlockByNum(num int64) (block *Block) {
	rsp := http.PostJsonD(cfg.GetAPI()+"/wallet/getblockbynum", map[string]any{"num": num})
	err := json.Unmarshal([]byte(rsp), &block)
	if err != nil {
		block = nil
		log.Errorf("LoadBlockByNum(%d):解析Json到Block到到对象失败：%v", num, err)
	}
	return
}

func ParseBlockData(data string) (toAddr string, amount float64) {
	//a9059cbb00000000000000000000004140f13870186644c717a1a28ec570f4a125215d1800000000000000000000000000000000000000000000000000000000002dc6c0
	//金额永远是后64位
	method := data[:8]
	if method == "a9059cbb" {
		//这种方法没有发送者地址,个人操作钱包转账属于这种
		toAddr = Hex42ToBase58("41" + data[32:72])
		_amount, _ := strconv.ParseInt(data[len(data)-64:], 16, 64)
		amount = float64(_amount) / 1e6
		return
	} else if method == "23b872dd" {
		//这种方法有发送者地址，代理转账属于这种，一般可以认定为不是个人通过钱包进行不同转账，而是代理转账
		//fromAddr = Hex42ToBase58("41" + data[32:72])
		//toAddr = Hex42ToBase58("41" + data[96:136])
		//_amount, _ := strconv.ParseInt(data[len(data)-64:], 16, 64)
		//amount = float64(_amount) / 1e6
	} else {
		//其他情况不做处理
		//log.Infof("method:%s", method)
	}
	return
}

func QueryTxFee(txId string) (spendFee float64) {
	rsp := http.PostJsonD(cfg.GetAPI()+"/wallet/gettransactioninfobyid", map[string]any{"value": txId})
	var data map[string]any
	err := json.Unmarshal([]byte(rsp), &data)
	if err != nil {
		log.Error(err)
		return
	}
	spendFee = data["fee"].(float64) / 1e6
	return
}

func QueryTxInfoById(txId string) (rsp string) {
	rsp = http.PostJsonD(cfg.GetAPI()+"/wallet/gettransactioninfobyid", map[string]any{"value": txId})
	return
}
